package com.example.audiodemo.endpoint;

import com.example.audiodemo.service.SpeakService;
import com.example.audiodemo.util.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@Component
@ServerEndpoint(value = "/websocket/speak")
@Slf4j
public class SpeakEndpoint {

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        ContextUtil.getBean(SpeakService.class).open(session);
    }

    @OnMessage
    public  void onMessage(byte[] message, Session session) {
        try {
            log.debug("websocket onMessage sessionId:{}", session.getId());
            ContextUtil.getBean(SpeakService.class).speak(session, message);
        } catch (Exception e) {
            log.error("websocket onMessage error sessionId:{}, message:{}", session.getId(), message);
        }
    }


    @OnError
    public void onError(Session session, Throwable error) {
        log.error("session error", error);
        ContextUtil.getBean(SpeakService.class).close(session);
    }

    @OnClose
    public void onClose(Session session) {
        ContextUtil.getBean(SpeakService.class).close(session);
    }
}
